//索书号信息
chrome.storage.local.get('items', ({ items }) => {
    if (items.length == 0) {
        $('#table').hide()
        document.querySelector('#btn').setAttribute('disabled', '1')
        document.querySelector('#del-btn').setAttribute('disabled', '1')
    } else {
        $('#none_text').hide()
        document.querySelector('#btn').removeAttribute('disabled')
        document.querySelector('#del-btn').removeAttribute('disabled')
        items.forEach(item => {
            let tr = document.createElement("div")
            tr.className = 'c'
            let td1 = document.createElement('div')
            td1.textContent = item
            let td2 = document.createElement('div')
            let cb = document.createElement('input')
            cb.setAttribute("type", "checkbox")
            cb.checked = true
            td2.appendChild(cb)
            tr.appendChild(td1)
            tr.appendChild(td2)
            let table = document.querySelector('#table')
            table.appendChild(tr)

        });
    }
})
//所在馆信息
chrome.storage.local.get('locations', ({ locations }) => {
    // console.log(locations)
    locations.forEach(data => {
        // console.log(data)
        let tr = document.createElement("div")
        tr.className = 'c'
        let td1 = document.createElement('div')
        td1.textContent = data.location
        let td2 = document.createElement('div')
        let cb = document.createElement('input')
        cb.setAttribute("type", "checkbox")
        cb.checked = data.checked
        cb.addEventListener('click', function () {
            data.checked = cb.checked
            chrome.storage.local.set({ locations: locations })
            chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
                chrome.tabs.sendMessage(tabs[0].id, locations);
            });
        })
        td2.appendChild(cb)
        tr.appendChild(td1)
        tr.appendChild(td2)
        $('#loc').append(tr)
    })
})

//复制选中
let btn = document.querySelector('#btn')
btn.addEventListener('click', function () {
    let text = ''
    $('#table').children().each(function (i) {
        let checked = $(this).children().eq(1).children().first().prop("checked")
        if (checked) {
            text += $(this).children().first().text().trim() + '\n'
        }
    })
    navigator.clipboard.writeText(text).then(
        () => {
            window.close();
        },
        () => {
            console.log("clipboard write failed");
        }
    );
})

//删除选中
let btnDel = document.querySelector('#del-btn')
btnDel.addEventListener('click', function () {
    chrome.storage.local.set({ items: [] });
    window.close();
})

